import time
import threading
import pcapy
import pcap
import dpkt
from netFunctions import *

class NetListener(threading.Thread):
    def __init__(self,interface,pc,inputbuffer,protocols=["any"]):
        threading.Thread.__init__(self)
        self._listeningInterface = interface
        self._buffer = inputbuffer
        self._running = False
        self._promisc = False
        self._filter = "ether dst "+getHwAddr(self._listeningInterface)
        self._snaplen = 65535
        self._immediate = True
        self._protocols = protocols
        self._pc = pc
        
    def isRunning(self):
        ''' Returns True if the listener is running, else will return False '''
        return self._running
    
    def setPromiscuousMode(self,value):
        self._promisc = value
        
    def getPromiscuousMode(self):
        return self._promisc
    
    def setSnaplen(self,value):
        if ( value > 0 and value <= 65535 ):
            self._snaplen = value
        else:
            return False
        
    def getSnaplen(self):
        return self._snaplen
    
    def setImmediateMode(self,bool):
        self._immediate = bool
        
    def getImmediateMode(self):
        return self._immediate
    
    def setCaptureFilter(self,filter):
        self._filter = filter
        
    def getCaptureFilter(self):
        return self._filter
    
    def stop(self):
        ''' Simple method to stop the listener '''
        self._running = False
        
    def _addPacketToBuffer(self,packet):
        self._buffer.append(packet)
        
    def run(self):
        self._running = True
        self._pc.setfilter(self._filter)
        self._pc.setnonblock(1)
        while self.isRunning():
            ts,payload = self._pc.next()
            frame = dpkt.ethernet.Ethernet(payload)
            if "any" in self._protocols or frame.type in self._protocols and frame.dst:
                self._addPacketToBuffer(frame)
        